package com.bank.manage.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.bank.manage.model.BankAccessWalletRecord;
import com.bank.manage.mapper.BankAccessWalletRecordMapper;
import com.bank.manage.model.BankOptCashRecords;
import com.bank.manage.model.param.BankQueryParam;
import com.bank.manage.model.vo.RequestVo;
import com.bank.manage.service.BankAccessWalletRecordService;
import com.bank.manage.utils.IPUtils;
import com.bank.manage.utils.SearcherRegion;
import com.bank.manage.utils.UniqueUtils;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * Wallet -- 钱包记录表 服务实现类
 * </p>
 *
 * @author grl
 * @since 2024-04-01
 */
@Service
@RequiredArgsConstructor
public class BankAccessWalletRecordServiceImpl extends ServiceImpl<BankAccessWalletRecordMapper, BankAccessWalletRecord> implements BankAccessWalletRecordService {

   private final HttpServletRequest request;

    @Override
    public RequestVo getRequestVo(BankAccessWalletRecord record){
        // 生成唯一值
        String requestId = UniqueUtils.generateRequestId(record);
        record.setRequestId(requestId);
        record.setCreateTime(LocalDateTime.now());
        record.setRequestJson(JSON.toJSONString(record));
        String ipAddress = IPUtils.getIpAddress(request);
        record.setAccessIp(ipAddress);
        record.setAccessRegion(SearcherRegion.getRegion(ipAddress));
        save(record);
        RequestVo vo = new RequestVo();
        vo.setRequestId(record.getRequestId());
        vo.setAccessWalletId(record.getId());
        return vo;
    }

    @Override
    public BankAccessWalletRecord queryUserNum(BankQueryParam param) {
        QueryWrapper wrapper = QueryWrapper.create().select(BankAccessWalletRecord::getUserNum).eq(BankAccessWalletRecord::getRequestId, param.getRequestId())
                .eq(BankAccessWalletRecord::getWalletNum, param.getWalletNum(), StringUtils.isNotBlank(param.getWalletNum())).from(BankAccessWalletRecord.class);
        return getOne(wrapper);
    }

    @Override
    public BankAccessWalletRecord queryUserNum(String requestId) {
        QueryWrapper wrapper = QueryWrapper.create().select(BankAccessWalletRecord::getUserNum).eq(BankAccessWalletRecord::getRequestId, requestId)
                .from(BankAccessWalletRecord.class);
        return getOne(wrapper);
    }
}
